package com.by.controller;

import com.alipay.api.AlipayClient;
import com.alipay.api.internal.util.file.IOUtils;
import com.alipay.api.request.AlipayTradePagePayRequest;
import com.by.bean.PayRequest;
import com.by.bean.PayResponse;
import com.by.bean.PaymentMethod;
import com.by.client.PaymentClient;
import com.by.client.factory.PaymentClientFactory;
import com.by.config.AliPayConfig;
import com.by.core.bean.ResultBean;
import com.by.core.controller.BaseController;
import com.by.service.PaymentService;
import com.by.utils.XmlUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.validation.Valid;
import java.io.IOException;
import java.nio.charset.StandardCharsets;
import java.util.HashMap;
import java.util.Map;


@RestController
@RequestMapping("/payment")
public class PaymentController extends BaseController {
    @Autowired
    PaymentService paymentService;

    @Autowired
    PaymentClientFactory paymentClientFactory;

    @Autowired
    AliPayConfig aliPayConfig;


    /**
     * 支付宝网页支付
     * @param orderSn
     * @param amount
     * @param response
     * @throws Exception
     */
    @GetMapping("/pay/web")
    public void payWeb(
            @RequestParam String orderSn,
            @RequestParam Double amount,
            HttpServletResponse response
    ) throws Exception {
        // 1. 获取支付宝客户端
        // 正确方式：通过接口调用
            PaymentClient client = paymentClientFactory.getClient(PaymentMethod.ALIPAY);
            String formHtml = client.createWebPayment(
                    orderSn,
                    amount.doubleValue(),
                    aliPayConfig.getNotifyUrl());

        response.setContentType("text/html;charset=utf-8");
        response.getWriter().write(formHtml);
        response.getWriter().flush();
    }


    @PostMapping("/create")
    public ResultBean<PayResponse> createPayment(@Valid @RequestBody PayRequest request){
        try{
            PayResponse response = paymentService.createPayment(request);
            return success("创建支付订单成功", response);
        }catch (RuntimeException e){
            return fail(e.getMessage());
        }

    }

    @PostMapping("/notify/alipay")
    public String handleAlipayNotify(HttpServletRequest request){
        // 解析支付宝回调参数并验签
        Map<String, String> params = parseAlipayParams(request);
        paymentService.handlePaymentNotify(params,"ALIPAY");
        return "success";
    }

    @PostMapping("/notify/wechat")
    public String handleWechatNotify(HttpServletRequest request) {
        // 仅处理微信回调
        Map<String, String> params = parseWechatParams(request);
        paymentService.handlePaymentNotify(params,"WECHAT");
        return "<xml><return_code>SUCCESS</return_code></xml>"; // 微信要求返回 XML
    }

    // 支付宝参数解析（无需判断路径）
    private Map<String, String> parseAlipayParams(HttpServletRequest request) {
        try {
            request.setCharacterEncoding("UTF-8");
            Map<String, String[]> requestParams = request.getParameterMap();
            Map<String, String> params = new HashMap<>();
            for (String key : requestParams.keySet()) {
                String[] values = requestParams.get(key);
                params.put(key, values != null && values.length > 0 ? values[0] : "");
            }
            return params;
        } catch (IOException e) {
            throw new RuntimeException("解析支付宝回调参数失败", e);
        }
    }

    // 微信参数解析（XML）
    private Map<String, String> parseWechatParams(HttpServletRequest request) {
        try {
            String xml = IOUtils.toString(request.getInputStream(), StandardCharsets.UTF_8);
            return XmlUtils.xmlToMap(xml);
        } catch (IOException e) {
            throw new RuntimeException("解析微信回调参数失败", e);
        }
    }

}
